package edu.whut.mall.admin.aspect;

import com.alibaba.fastjson.JSON;
import edu.whut.mall.admin.shiro.util.ShiroUtil;
import edu.whut.mall.mapper.SysLogMapper;
import edu.whut.mall.model.SysLog;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;

/**
 * @program: d9lab-mall
 * @description: 管理员操作日志
 * @author: Wayne
 * @create: 2020-04-20 14:16
 **/
@Aspect
@Component
@RequiredArgsConstructor
@Slf4j
public class SysLogAspect {

    private final SysLogMapper sysLogMapper;

    @Pointcut("@annotation(edu.whut.mall.admin.annotations.LogAnnotation)")
    public void sysLog() {
    }

    @Around("sysLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        SysLog sysLog=new SysLog();
        Object result = joinPoint.proceed();
        Signature signature = joinPoint.getSignature();
        sysLog.setUsername(ShiroUtil.getUserEntity().getAdminName());
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method.isAnnotationPresent(ApiOperation.class)) {
            ApiOperation desc = method.getAnnotation(ApiOperation.class);
            sysLog.setDescription(desc.value());
        }
        long endTime = System.currentTimeMillis();
        sysLog.setParams(JSON.toJSONString(getParameter(method, joinPoint.getArgs())));
        if(result!=null) {
            sysLog.setResult("操作成功");
        }
        else{
            sysLog.setResult("操作失败");
        }
        sysLog.setSpendTime((int) (endTime - startTime));
        sysLog.setStartTime(new Date());
        sysLog.setUrl(request.getRequestURL().toString());
        sysLogMapper.insert(sysLog);

        return result;
    }

    /**
     * 根据方法和传入的参数获取请求参数
     */
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }
}
